﻿namespace WLFramework.IoC
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    internal abstract class BaseIoCRegisterService : IIocRegisterService
    {
        private object _instance;
        private readonly object _mutex = new object();

        private readonly Func<IIocContainer, object> _creation;

        internal BaseIoCRegisterService(Func<IIocContainer, object> create)
        {
            this._creation = create;
            this.HasInstance = false;
        }

        public bool HasInstance { get; private set; }
        public abstract string Type { get; }

        public object GetInstance(IIocContainer ioc, bool createNew)
        {
            if (createNew)
            {
                return _creation(ioc);
            }

            if (this.HasInstance)
            {
                return _instance;
            }

            lock (this._mutex)
            {
                if (this.HasInstance)
                {
                    return this._instance;
                }

                this._instance = _creation(ioc);
                this.HasInstance = true;

                return this._instance;
            }
        }

        public bool DestroyInstance()
        {
            if (!this.HasInstance)
            {
                return false;
            }

            lock (this._mutex)
            {
                if (!this.HasInstance)
                {
                    return false;
                }

                this._instance = null;
                this.HasInstance = false;
                return true;
            }
        }
    }
}
